package com.eagle.roomsearch.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/*
*比較繞的Redis配置：類比JDBC
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {

        return new RedisCacheManager(redisTemplate);
    }

    //自定義初始化配置
    @Bean(name = "redisSerializer")
    public RedisSerializerConfig redisSerializer() {

        return new RedisSerializerConfig();
    }

    /*  @Bean(name = "jedisConnectionFactory")
      public JedisConnectionFactory connectionFactory() {
          JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
          jedisConnectionFactory.setHostName("localhost");
          jedisConnectionFactory.setDatabase(1);
          jedisConnectionFactory.setPort(6379);
          return jedisConnectionFactory;
      }
  */
    @Bean(name = "objectRedisTemplate")
    public RedisTemplate<String, Object> objectRedisTemplate(RedisConnectionFactory factory,
                                                             @Qualifier("redisSerializer") RedisSerializerConfig redisSerializer) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean(name = "websocketRedisTemplate")
    public RedisTemplate<String, Object> websocketRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setDefaultSerializer(new WebsocketSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

